package com.pirestupppai.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.support.multidex.MultiDex;
import android.util.Log;
import android.view.WindowManager;

import com.mob.MobSDK;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import com.pirestupppai.common.Constant;
import com.pirestupppai.utils.CrashHandler;
import com.pirestupppai.utils.FaceConversionUtil;
import com.pirestupppai.utils.FileUtil;
import com.pirestupppai.utils.SharedPreferenceUtil;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.MsgConstant;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import io.rong.imkit.RongIM;
import mabeijianxi.camera.VCamera;


/**
 * 初始化数据及服务
 *
 * @author: xiaoluo
 * @date: 2016-12-20 17:53
 */
public class BaseApplication extends Application {
    private static final String TAG = BaseApplication.class.getSimpleName();

    private static Context mAppContext;
    private static BaseApplication instance;
    private RefWatcher refWatcher;

    // 记录当前栈里所有的activity
    private List<Activity> mActivityList = new ArrayList<Activity>();

    public static BaseApplication getInstance() {
        if (instance == null) {
            instance = new BaseApplication();
        }
        return instance;
    }

    public static RefWatcher getRefWatcher(Context context) {
        BaseApplication application = (BaseApplication) context
                .getApplicationContext();
        return application.refWatcher;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mAppContext = this.getApplicationContext();

        // 注册Crash捕捉上报系统
        CrashHandler.getInstance().init(mAppContext);

        // 内存泄漏分析
        if (LeakCanary.isInAnalyzerProcess(this)) {
            return;
        }
        LeakCanary.install(this);

        // 获取屏幕宽高
        getScreen();

        // 获取状态栏高度
        getStatusBarHeight();

        // 初始化sharesdk
        // 通过代码注册你的AppKey和AppSecret
        MobSDK.init(mAppContext,"6ad0e19b7a25","9499bf85f7ebfd5d33fe7b182ed53b6e");

        // 友盟推送
        initPushSdk();

        // 初始化表情数据
//        initFace();

        // 初始化融云
        RongIM.init(this);

        // 初始化相机
//        initVideo(this);

        // 初始化Logger    PRETTY_LOGGER
        Logger.addLogAdapter(new AndroidLogAdapter());
    }

    public static void initVideo(Context context) {
        // 设置拍摄视频缓存路径
//        File dcim = Environment
//                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
//        if (DeviceUtils.isZte()) {
//            if (dcim.exists()) {
//                VCamera.setVideoCachePath(dcim + "/tupai/");
//            } else {
//                VCamera.setVideoCachePath(dcim.getPath().replace("/sdcard/",
//                        "/sdcard-ext/")
//                        + "/tupai/");
//            }
//        } else {
            VCamera.setVideoCachePath(FileUtil.SDPath + "/tupai/video/");
//        }
        VCamera.setDebugMode(true);
        VCamera.initialize(context);
    }



    /**
     * 初始化表情
     */
    private void initFace() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                FaceConversionUtil.getInstace().getFileText(mAppContext);
            }
        }).start();
    }

    /**
     * 友盟推送初始化
     */
    private void initPushSdk() {
        PushAgent mPushAgent = PushAgent.getInstance(mAppContext);
        mPushAgent.setDebugMode(true);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
                SharedPreferences.Editor editor = SharedPreferenceUtil.getEditor();
                editor.putString(Constant.SPKey.DEVICE_TOKEN, deviceToken);
                editor.apply();

                Log.d(TAG, deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
                Log.d(TAG, s + ":" + s1);
            }
        });

        /*
         * 可自定义用户点击通知栏时的后续动作,需要后台发消息时选择自定义行为
         *
         *  如果在Activity中调用此接口，若应用进程关闭，则设置的接口会无效。
         *  UmengNotificationClickHandler是在BroadcastReceiver中被调用，
         *  因此若需启动Activity，需为Intent添加Flag：Intent.FLAG_ACTIVITY_NEW_TASK，否则无法启动Activity。
         */
        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
                Log.d(TAG, msg.custom);
            }
        };
        mPushAgent.setNotificationClickHandler(notificationClickHandler);


        /*
         * 自定义消息
         */
        UmengMessageHandler messageHandler = new UmengMessageHandler() {
            @Override
            public void dealWithNotificationMessage(Context context, UMessage uMessage) {
                super.dealWithNotificationMessage(context, uMessage);
            }
        };
        mPushAgent.setMessageHandler(messageHandler);

        // sdk关闭通知声音   NOTIFICATION_PLAY_SDK_ENABLE
        mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);
    }


    /**
     * 获取屏幕宽高
     */
    private void getScreen() {
        Point outSize = new Point();
        WindowManager windowManager = (WindowManager) mAppContext.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getSize(outSize);
        Constant.WIDTH_OF_SCREEN = outSize.x;
        Constant.HEIGHT_OF_SCREEN = outSize.y;

    }

    private void getStatusBarHeight() {
        Class<?> c;

        Object obj;

        Field field;

        int x, sbar = 0;

        try {

            c = Class.forName("com.android.internal.R$dimen");

            obj = c.newInstance();

            field = c.getField("status_bar_height");

            x = Integer.parseInt(field.get(obj).toString());

            sbar = mAppContext.getResources().getDimensionPixelSize(x);

        } catch (Exception e1) {

            e1.printStackTrace();

        }

        Constant.HEIGHT_OF_STATUSBAR = sbar;

    }

    // 解决65K方法限制
    // 如果有自己的Application，继承MulitDexApplication。
    // 如果当前代码已经继承自其它Application没办法修改那也行，就重写 Application的attachBaseContext()这个方法。
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    /**
     * 获取AppContext
     */
    public static Context getAppContext() {
        return mAppContext;
    }

    /**
     * 新开了activity
     */
    public void addActivity(Activity activity) {
        mActivityList.add(activity);
    }


    /**
     * 结束指定类名的Activity
     */
    public void finishActivityClass(Class<?> cls) {
        if (mActivityList != null) {
            for (Activity activity : mActivityList) {
                if (activity.getClass().equals(cls)) {
                    this.mActivityList.remove(activity);
                    finishActivity(activity);
                    break;
                }
            }
        }
    }


    /**
     * 结束指定activity
     */
    public void finishActivity(Activity activity) {

        if (activity != null) {
            this.mActivityList.remove(activity);
            activity.finish();
        }
    }


}
